<template>
  <div class="message-panel-container">
    <div class="recently-list-container">
      <div
          class="chat-item"
          :class="currentSelectedId === chat.id ? 'chat-item__selected' : ''"
          v-for="chat in chatList"
          :key="chat.id"
          v-ripple
          @click="handleChatClick(chat.id)">
        <v-avatar>
          <img
              :src="chat.avatar"
              alt="John">
        </v-avatar>
        <div class="name-and-message">
          <div class="username">
            {{ chat.friendBeiZu === ""||chat.friendBeiZu === null ? chat.nickname : chat.friendBeiZu }}
          </div>
          <div class="message" v-if="chat.messageType === 'image'">
            [图片]
          </div>
          <div class="message" v-if="chat.messageType === 'file'">
            [文件]
          </div>
          <div class="message" v-if="chat.messageType === 'text'">
            {{chat.lastMessage}}
          </div>
        </div>
        <div class="time-and-status">
          <div class="time">
            {{ chat.time | formatTime }}
          </div>
          <v-badge
              class="read-status"
              color="#ff7456"
              offset-x="10px"
              offset-y="15px"
              dot>
            <div class="read-status"></div>
          </v-badge>
        </div>
      </div>
    </div>
    <div class="chat-container">
      <chatFrame
          ref="chatFrame"
          v-if="showChatFrame"
          :userInfo="getCurrentChat()"/>
    </div>
  </div>
</template>

<script>
import chatFrame from "@/components/chat/chatFrame/chatFrame";
import {getMyChatList, getMyFriendList, getMyGroupList, getUserInfo} from "../../../api";

export default {
  name: "messagePanel",
  components: {
    chatFrame
  },
  data() {
    return {
      chatList: [],
      currentSelectedId: -1,
      showChatFrame: false
    }
  },
  methods: {
    getCurrentChat() {
      let currentChat
      this.chatList.forEach(chat => {
        if (chat.id === this.currentSelectedId) {
          currentChat = chat
        }
      })
      console.log(currentChat)
      return currentChat
    },
    handleChatClick(id) {
      console.log(id)
      this.currentSelectedId = id;
      this.showChatFrame = false;
      this.$nextTick(() => {
        this.showChatFrame = true;
      });
    },
    async getMyChatList() {
      const chatListRes = await getMyChatList();
      chatListRes.success ? this.chatList = chatListRes.data : console.log(chatListRes);
      const friendListRes = await getMyFriendList();
      let friendList = friendListRes.data;
      this.$emit('friendList', friendList);
      const groupListRes = await getMyGroupList();
      let groupList = groupListRes.data;
      this.$emit('groupList', groupList);
      friendList.forEach(friend => {
        let join = {
          id: friend.roomId.replace(this.myInfo.id, ""), //roomId去掉我的Id，就是friendId
          conversationType: 'FRIEND',
          createDate: new Date(),
          isGroup: false,
          roomId: friend.roomId,
          myId: this.myInfo.id,
          myAvatar: this.myInfo.avatar,
          myNickname: this.myInfo.nickname,
          nickname: friend.nickname,
          avatar: friend.avatar,
          username: friend.username,
        };
        this.$socket.emit('join', join);
      });
      if (this.chatList.length > 0) {
        this.currentSelectedId = this.chatList[0].id;
        this.showChatFrame = false;
        this.$nextTick(() => {
          this.showChatFrame = true;
        });
      }
    },
    receiveMessage(msg) {
      const roomId = msg.roomId;
      this.chatList.forEach(item => {
        if (item.id === roomId) {
          item.lastMessage = item.messageType === 'image' ? '[图片]' : msg.message;
        }
      });
    },
    async openChat(roomId) {
      console.log(roomId)
      let flag = true
      this.chatList.forEach(chat => {
        if (chat.id === roomId) {
          flag = false
        }
      })
      if (flag) {
        let friendId = roomId.replaceAll(this.myInfo.id, "").replaceAll("-", "")
        let res = await getUserInfo(friendId);
        let userInfo = res.data.user;
        let friendBeiZu = this.myInfo.friendBeiZhu;
        let friendBeiZuValue = ""
        for (const friendBeiZuElement in friendBeiZu) {
          if (friendId === friendBeiZuElement) {
            friendBeiZuValue = friendBeiZu[friendId]
          }
        }
        console.log(userInfo)
        let messageItem = {
          id: roomId,
          lastMessage: "",
          avatar: userInfo.avatar,
          nickname: userInfo.nickname,
          username: userInfo.username,
          messageType: "text",
          time: new Date(),
          friendBeiZu: friendBeiZuValue
        }
        this.chatList.push(messageItem)
        this.$forceUpdate();
      }
      this.handleChatClick(roomId)
    },
    updateColor() {
      this.customerColor = sessionStorage.getItem('custom-color');
    }
  },
  filters: {
    formatTime(time) {
      let messageDate = new Date(time);
      let nowDate = new Date();
      let messageTime = {
        year: messageDate.getFullYear(),
        month: messageDate.getMonth() + 1,
        day: messageDate.getDate(),
        hour: messageDate.getHours().toString().padStart(2, '0'),
        min: messageDate.getMinutes().toString().padStart(2, '0'),
        second: messageDate.getSeconds()
      }
      let nowTime = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        day: nowDate.getDate()
      }
      if (messageTime.year === nowTime.year && messageTime.month === nowTime.month && messageTime.day === nowTime.day) {
        return `${messageTime.hour}:${messageTime.min}`;
      } else if (messageTime.year === nowTime.year && messageTime.month === nowTime.month && messageTime.day + 1 === nowTime.day) {
        return `昨天`;
      } else {
        return `${messageTime.month}:${messageTime.day}`;
      }
    }
  },
  watch: {
    customerColor(nval) {
      this.$refs.chatFrame.updateColor();
    }
  },
  mounted() {
    this.myInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.getMyChatList();
  },
  created() {
  }
}
</script>

<style lang="scss" scoped>
@import 'messagePanel.scss';
</style>